import buffer from '@ohos.buffer';
/**
 * 网络工具类
 */
export function resolveIP(ip) {
  if (ip < 0 || ip > 0xFFFFFFFF) {
    throw ('The number is not normal!');
  }
  return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
}

export class GeneralFunc {
  public static utf8ToHex(utf8String: string): ArrayBuffer {
    let headBuffer : ArrayBuffer = new ArrayBuffer(6);
    let headUBuffer : Uint8Array = new Uint8Array(headBuffer);
    // 定义16进制的数据
    let headValues = [0x7E, 0x01, 0x30, 0x30, 0x30, 0x30];
    // 将16进制数据转换为十进制并写入到buffer中
    for (let i = 0; i < headValues.length; i++) {
      headUBuffer[i] = headValues[i];
    }
    let headBufferLen : number = headBuffer.byteLength;

    // 将数据转换为 Buffer
    let order: buffer.Buffer = buffer.from(utf8String, 'utf8');
    let orderBuffer : ArrayBuffer = order.buffer;
    let orderBufferLen : number = orderBuffer.byteLength;

    let endBuffer : ArrayBuffer = new ArrayBuffer(2);
    let endUBuffer : Uint8Array = new Uint8Array(endBuffer);
    // 定义16进制的数据
    let endValues = [0x3B, 0x03];
    // 将16进制数据转换为十进制并写入到buffer中
    for (let i = 0; i < endValues.length; i++) {
      endUBuffer[i] = endValues[i];
    }
    let endBufferLen : number = endBuffer.byteLength;
    // 合并指令
    let mergedBuffer : ArrayBuffer = new ArrayBuffer(headBufferLen + orderBufferLen + endBufferLen);
    let mergedView : Uint8Array = new Uint8Array(mergedBuffer);
    mergedView.set(new Uint8Array(headBuffer), 0);
    mergedView.set(new Uint8Array(orderBuffer), headBufferLen);
    mergedView.set(new Uint8Array(endUBuffer), headBufferLen + orderBufferLen);
    return mergedBuffer;
  }
}